package lc29;

public class Lc29 {

    public int divide(int dividend, int divisor) {
        if(dividend == 0){
            return 0;
        }
        if(dividend == Integer.MIN_VALUE && divisor == -1){
            return Integer.MAX_VALUE;
        }
        int sign = 1;
        if((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0)){
            sign = -1;
        }
        // 因为 Integer.MIN_VALUE * -1 会溢出，所以转成负数运算
        dividend = dividend > 0 ? -dividend : dividend;
        divisor = divisor > 0 ? -divisor : divisor;
        return sign * helper(dividend, divisor);

    }

    private int helper(int a, int b) {
        // a=-1,b=-5
        if(a >= b){
            return a > b ? 0 : 1;
        }
        int count = 1; // 倍数
        int res = 0; // 商
        int tb = b;
        while(a <= tb && tb < 0){
            a -= tb;
            res += count;
            tb += tb;
            count += count;
        }
        return res + helper(a, b);
    }

    public static void main(String[] args) {
        Lc29 lc29 = new Lc29();
        lc29.divide(10000, 1);

    }

}
